const statusEnum = {
  0: 'ALL',
  1: '未付款',
  2: '未发货',
  3: '退款'
};
Page({
  data: {
    count: 0,
    sum: '0.00',
    superchecked:false,
    address: '杭州市 余杭区  闲林街道  翡翠城东北区',
    shippingFrom: {
      type: "同城配送",
      name: "屈臣氏 (亲橙里店)",
    },
    shippingTime: {
      payTime: "11:00",
      receiveDay: "今天",
      receiveFormatDay: "04月16日",
    },
    orderList: [
    ],
  },
  async commit() {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    console.log(userInfo);
    if(userInfo==null){
      abridge.alert({
        title: "获取个人信息失败，请稍后"
      })
      return
    }
    console.log(this.data.orderList);
    const commodity = this.data.orderList[0];
    const carIds = [];
    const orderGoods = commodity.commodity.map(item => {
      carIds.push(item.id);
      return {
        title: item.title,
        description: item.description,
        image: item.image,
        skuId: item.productId,
        price: item.price,
        count: item.num
      };
    });
    //1，创建订单
    const response =  await my.fncontext.callFunction({
      name:"orderAdd",
      data:{
        "totalCount":commodity.sum,
        "totalAmount":commodity.total,
        "freight":200,
        "payType":"ALIPAY",
        "addressInfo":null,
        "userId":userInfo.user_id,
        "orderGoods":orderGoods
    }
    });
    console.log("修改订单",response);
    //2，支付
    await this.pay(response.result.id,userInfo.user_id,response.result.orderNumber,response.result.totalAmount);
    //4，删除购物车数据
    await this.deleteShopeCarInfo(carIds);
    //5，跳转订单中心
    await my.reLaunch({ 
      url: '/pages/my-order/my-order',
  })
  },
  async pay(...params) {
    const id = params[0];
    const userId = params[1];
    const tradeNo = params[2];
    const total = params[3];
    console.log("params",params);
    if(!userId){
      my.showToast({
        content:'输入userId',
        duration:1000
      });
      return;
    }
    // 云环境初始化 
    await my.fncontext.init(); 
    const trade  = await my.fncontext.callFunction({
      name:"alipayTradeCreate",
      data:{
        "tradeNo": tradeNo,
        "totalAmount": total,
        "subject":"商品",
        "buyerId":userId
      }
    })
    console.log('trade', trade);
    if(trade!=null&&trade.result.code=="10000"){
      try {
        const result = await this.tradePaySync(trade.result);
        console.log("支付结果：",result);       
        // 执行成功操作逻辑
        if(result.resultCode!=null&&result.resultCode=="9000"){
          await this.updateOrderStatus(id,statusEnum[2]);
        }
      } catch (error) {
        console.error(error); // 处理错误
      }
    }
  },
  async updateOrderStatus(...params){
    const orderId = params[0];
    const orderStatus = params[1];
    const response =  await my.fncontext.callFunction({
      name:"orderUpdate",
      data:{
        "id":orderId,
        "status":orderStatus
      }
    });
    console.log("修改订单状态",response);
  },
  async tradePaySync(trade) {
    console.log("支付参数：",trade.trade_no);   
    return new Promise((resolve, reject) => {
      my.tradePay({
        tradeNO: trade.trade_no,
        success: function (res) {
          resolve(res); // 异步操作成功，解析Promise，并返回结果
        },
        fail: function (error) {
          reject(error); // 异步操作失败，拒绝Promise，并返回错误信息
        }
      });
    });
  },
  //删除相应购物车数据
  async deleteShopeCarInfo(...params){
    const carIds = params[0];
    const response    =  await my.fncontext.callFunction({
      name:"shopCarDelete",
      data:{
        "ids":carIds
      }
    });
  },
  onLoad() { 
    console.log(this.data); 
    my.setNavigationBar({
      title: '购物车',
    });
    const eventChannel = this.getOpenerEventChannel();
    let order = null;
    // B 页面 接收 A 页面传过来的数据。
    eventChannel.on('orderList', data => {
      order = data.data;
    });
    // B 页面向 A 页面 传值
    eventChannel.emit('pageB_Data', {
      message: 'hello～ 我是 pageB',
    });
    console.log(order); 
    this.setData({
      orderList:order,
      count:order[0].sum,
      sum:order[0].total
    })
    console.log(this.data); 
  }
});
